#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>

#define NUM 1024
#define SIZE 50

char cmd_list[NUM];
char *argv[SIZE];
int main()
{
    while(1)
    {
        //打印提升信息
        printf("[defa@VM-myshell ~]$ ");
        fflush(stdout);
        memset(cmd_list,'\0',sizeof cmd_list);
        //获取用户的信息
        if(fgets(cmd_list,sizeof cmd_list,stdin)==NULL)
        {
            continue;
        }
        //把输入的\n去掉
        cmd_list[strlen(cmd_list)-1]='\0';
        //把字符串进行解开放在数组中
        argv[0]=strtok(cmd_list," ");
        int index=1;
        if(strcmp(argv[0],"ls")==0)
        {
            argv[index++]="--color=auto";
        }
        if(strcmp(argv[0],"ll")==0)
        {
            argv[0]="ls";
            argv[index++]="-l";
            argv[index++]="--color=auto";
        }
        while(argv[index++]=strtok(NULL," "));
        if(strcmp(argv[0],"cd")==0)
        {
             if(argv[1] != NULL) chdir(argv[1]); //cd path, cd ..

            continue;
        }

        //子进程解析信息，父进程等待和检测子进程
        pid_t id=fork();
        if(id==0)
        {
            printf("子进程进行\n");
            execvp(argv[0],argv);
            exit(1);
        }
        int status=0;
        pid_t result=waitpid(id,&status,0);
        if(result>0)
        {
            printf("子进程退出码：%d\n",WEXITSTATUS(status));
        }
    }
    return 0;
}
